package com.fvision.camera.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;

import com.fvision.camera.iface.FroegroundIface;
import com.fvision.camera.manager.CmdManager;
import com.fvision.camera.service.ForegroundService;
import com.fvision.camera.utils.Const;
import com.fvision.camera.utils.LogUtils;

public class FroegroundReceiver extends BroadcastReceiver  {
	ForegroundService service;
	FroegroundIface iface;
    public IntentFilter filter = new IntentFilter();

	public FroegroundReceiver(Context context, FroegroundIface iview){
		service = (ForegroundService)context;
		iface = iview;
		filter.addAction(Const.BROAD_CAST_SHOW_FLOATWINDOW);
		filter.addAction(Const.BROAD_CAST_HIDE_FLOATWINDOW);
		filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
		filter.addAction(Const.BROAD_CAST_SYNC_TIME);
		filter.addAction(Intent.ACTION_TIME_TICK);
		filter.addAction(Intent.ACTION_MEDIA_EJECT);
	}

	public Intent registerReceiver() {
		return service.registerReceiver(this, filter);
	}

	public void unregisterReceiver() {
		service.unregisterReceiver(this);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		LogUtils.d("111111 "+intent.getAction());
//		iMainView.showToast(intent.getAction());
	    if(intent.getAction().equals(Const.BROAD_CAST_SHOW_FLOATWINDOW)){
			iface.showPopuWindow();
	    }else if(intent.getAction().equals(Const.BROAD_CAST_HIDE_FLOATWINDOW)){
			iface.hidePopuWindow();
		}else if(intent.getAction().equals(Const.BROAD_CAST_SYNC_TIME)
				|| intent.getAction().equals(Intent.ACTION_TIME_TICK)
				|| intent.getAction().equals(Intent.ACTION_TIME_CHANGED)
				){
			if(isSync()){
				iface.syncTime();
			}
		}else if(intent.getAction().equals(Intent.ACTION_MEDIA_EJECT)){
			iface.pullUsb();
		}
	};

	private boolean isSync(){
		long lastSyncTime = CmdManager.getInstance().getLastSyncTime();
		long now = System.currentTimeMillis();
		if(now - lastSyncTime > 60 * 60 * 1000){
			return true;
		}
		return false;
	}
}
